<template>
  <div class="loan-list-container">
    <!-- 顶部导航栏 -->
    <div class="loan-list-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">我的贷款</div>
      <div class="placeholder"></div>
    </div>

    <!-- 内容区域 -->
    <div class="loan-list-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="!loanStore.hasLoans" class="empty-container">
        <el-empty description="暂无贷款记录">
          <el-button type="primary" @click="goToApply">
            立即申请
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="loan-list">
        <!-- 移动端卡片列表 -->
        <div class="loan-cards">
          <div 
            v-for="loan in loanStore.state.loans" 
            :key="loan.id" 
            class="loan-card"
            @click="viewLoanDetail(loan.id)"
          >
            <div class="loan-card-header">
              <div class="loan-no">{{ loan.loanNo }}</div>
              <el-tag :type="getLoanStatusType(loan.status)" size="small">
                {{ loan.statusText }}
              </el-tag>
            </div>
            
            <div class="loan-card-body">
              <div class="loan-amount">
                <span class="amount-label">贷款金额</span>
                <span class="amount-value">¥{{ formatMoney(loan.amount) }}</span>
              </div>
              
              <div class="loan-info">
                <div class="info-item">
                  <span class="info-label">期限</span>
                  <span class="info-value">{{ loan.period }}个月</span>
                </div>
                <div class="info-item">
                  <span class="info-label">利率</span>
                  <span class="info-value">{{ loan.interestRate }}%</span>
                </div>
              </div>
              
              <div class="loan-time">
                申请时间：{{ formatDate(loan.applyTime) }}
              </div>
            </div>
            
            <div class="loan-card-actions" @click.stop>
              <el-button
                type="primary"
                size="small"
                plain
                @click="viewLoanDetail(loan.id)"
              >
                查看
              </el-button>
              <el-button
                v-if="loan.status === 0"
                type="danger"
                size="small"
                plain
                @click="cancelLoan(loan.id)"
              >
                取消
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 贷款详情对话框 -->
    <el-dialog
      v-model="loanDetailVisible"
      title="贷款详情"
      width="95%"
      :close-on-click-modal="false"
      class="mobile-dialog"
    >
      <div v-if="currentLoan" class="loan-detail">
        <div class="detail-section">
          <div class="detail-header">
            <div class="loan-no">{{ currentLoan.loanNo }}</div>
            <el-tag :type="getLoanStatusType(currentLoan.status)">
              {{ currentLoan.statusText }}
            </el-tag>
          </div>
          
          <div class="detail-amount">
            <div class="amount-label">贷款金额</div>
            <div class="amount-value">¥{{ formatMoney(currentLoan.amount) }}</div>
          </div>
        </div>
        
        <div class="detail-info">
          <div class="info-row">
            <span class="label">贷款期限</span>
            <span class="value">{{ currentLoan.period }}个月</span>
          </div>
          <div class="info-row">
            <span class="label">贷款利率</span>
            <span class="value">{{ currentLoan.interestRate }}%</span>
          </div>
          <div class="info-row">
            <span class="label">贷款用途</span>
            <span class="value">{{ currentLoan.purpose || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">申请时间</span>
            <span class="value">{{ formatDate(currentLoan.applyTime) }}</span>
          </div>
          <div class="info-row">
            <span class="label">审批时间</span>
            <span class="value">{{ currentLoan.approveTime ? formatDate(currentLoan.approveTime) : '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">放款时间</span>
            <span class="value">{{ currentLoan.loanTime ? formatDate(currentLoan.loanTime) : '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">还款开始时间</span>
            <span class="value">{{ currentLoan.repayStartTime ? formatDate(currentLoan.repayStartTime) : '-' }}</span>
          </div>
        </div>
        
        <div v-if="currentLoan.status >= 4" class="repayment-section">
          <el-button 
            type="primary" 
            class="repayment-button"
            @click="viewRepaymentPlan(currentLoan.id)"
          >
            查看还款计划
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useLoanStore, useUserStore } from 'store';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import loanService from '@/services/loanService';

// 国际化
const { t } = useI18n();

// 路由
const router = useRouter();

// Store
const loanStore = useLoanStore();
const userStore = useUserStore();

// 加载状态
const loading = ref(false);

// 贷款详情对话框
const loanDetailVisible = ref(false);
const currentLoan = ref(null);

// 获取贷款状态类型
const getLoanStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 申请中
    1: 'warning', // 审核中
    2: 'danger',  // 已拒绝
    3: 'success', // 已通过
    4: 'success', // 已放款
    5: 'primary', // 还款中
    6: 'success', // 已结清
    7: 'danger'   // 已逾期
  };
  return statusMap[status] || 'info';
};

// 格式化金额
const formatMoney = (amount) => {
  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 导航到贷款申请页面
const goToApply = () => {
  router.push('/loan/apply');
};

// 查看贷款详情
const viewLoanDetail = async (id) => {
  try {
    const loan = await loanService.getLoanDetail(id);
    if (loan) {
      currentLoan.value = loan;
      loanDetailVisible.value = true;
    }
  } catch (error) {
    console.error('获取贷款详情失败:', error);
    ElMessage.error('获取贷款详情失败');
  }
};

// 查看还款计划
const viewRepaymentPlan = (loanId) => {
  router.push(`/loan/repayment-plan/${loanId}`);
};

// 取消贷款
const cancelLoan = (id) => {
  ElMessageBox.confirm(
    t('loan.cancelConfirm'),
    t('loan.cancelTitle'),
    {
      confirmButtonText: t('loan.confirm'),
      cancelButtonText: t('loan.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    try {
      const success = await loanService.cancelLoan(id);
      if (success) {
        ElMessage.success(t('loan.cancelSuccess'));
        // 重新获取贷款列表
        await fetchLoanList();
      }
    } catch (error) {
      console.error('取消贷款失败:', error);
      ElMessage.error('取消贷款失败');
    }
  }).catch(() => {
    // 取消操作
  });
};

// 获取贷款列表
const fetchLoanList = async () => {
  try {
    const userId = userStore.userId;
    await loanService.getLoanList(userId);
  } catch (error) {
    ElMessage.error('获取贷款列表失败');
  }
};

// 获取贷款列表
onMounted(async () => {
  loading.value = true;
  try {
    await fetchLoanList();
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped lang="scss">
.loan-list-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.loan-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background-color: #3a4a7f;
  color: white;
  padding: 0 15px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.placeholder {
  width: 20px;
}

.loan-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.loading-container, .empty-container {
  padding: 40px 20px;
  text-align: center;
}

.loan-cards {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.loan-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
}

.loan-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  .loan-no {
    font-size: 14px;
    color: #666;
    font-weight: 500;
  }
}

.loan-card-body {
  margin-bottom: 16px;
}

.loan-amount {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  .amount-label {
    font-size: 14px;
    color: #666;
  }
  
  .amount-value {
    font-size: 20px;
    font-weight: bold;
    color: #409EFF;
  }
}

.loan-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .info-label {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
  }
  
  .info-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }
}

.loan-time {
  font-size: 12px;
  color: #999;
}

.loan-card-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

// 对话框样式
.mobile-dialog {
  :deep(.el-dialog) {
    margin: 5vh auto;
    border-radius: 12px;
  }
  
  :deep(.el-dialog__header) {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #eee;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.loan-detail {
  .detail-section {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
  }
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .loan-no {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  
  .detail-amount {
    text-align: center;
    
    .amount-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      display: block;
    }
    
    .amount-value {
      font-size: 28px;
      font-weight: bold;
      color: #409EFF;
    }
  }
  
  .detail-info {
    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        font-size: 14px;
        color: #666;
      }
      
      .value {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .repayment-section {
    margin-top: 20px;
    text-align: center;
    
    .repayment-button {
      width: 100%;
      height: 44px;
      font-size: 16px;
      border-radius: 22px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .loan-list-content {
    padding: 10px;
  }
  
  .loan-cards {
    gap: 10px;
  }
  
  .loan-card {
    padding: 12px;
  }
  
  .loan-amount .amount-value {
    font-size: 18px;
  }
}
</style>